package com.dushibao.manage.menu;

import com.alibaba.fastjson2.JSON;
import com.dushibao.entity.Menu;
import com.dushibao.service.MenuService;
import com.dushibao.service.impl.MenuServiceImpl;
import com.dushibao.view.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/menu/add")
public class AddServlet extends HttpServlet {
    MenuService menuService = new MenuServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Map<String,Object> maps = new HashMap<>();

        //如果有id说明是编辑
        if(id !=null && id.length()>0){
            Menu menu = menuService.getById(Long.parseLong(id));
            maps.put("editObj",menu);
        }

        ModelAndView mv = new ModelAndView("menu/add",maps);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader bw = req.getReader();
        String json = bw.readLine();

        Menu menu = JSON.parseObject(json, Menu.class);

        Integer ret = menuService.saveOrUpdate(menu);
        resp.getWriter().write(ret.toString());

    }
}
